import Vue from 'vue'
import VueRouter from 'vue-router'
// import login from '../views/login'
// import register from '../views/register'
import layout from '../views/layout'
// import detail from '../views/detail'
// import article from '../views/layout-routes/article'
// import collect from '../views/layout-routes/collect'
// import like from '../views/layout-routes/like'
// import my from '../views/layout-routes/my'
import { getToken } from '@/utils/storage'
import ArticleItem from '@/components/article-item'
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: 'layout' },
  { path: '/login', component: () => import('@/views/login') },
  { path: '/register', component: () => import('@/views/register') },
  {
    path: '/layout',
    component: layout,
    children: [
      { path: '/', redirect: 'article' },
      { path: 'article', component: () => import('@/views/layout-routes/article') },
      { path: 'collect', component: () => import('@/views/layout-routes/collect') },
      { path: 'like', component: () => import('@/views/layout-routes/like') },
      { path: 'my', component: () => import('@/views/layout-routes/my') }
    ]
  },
  { path: '/detail/:id', component: () => import('@/views/detail') }

]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register'] // 白名单列表，记录无需权限访问的所有页面

router.beforeEach((to, from, next) => {
  const token = getToken()
  // 如果有token，直接放行
  if (token) {
    next()
  } else {
    // 没有token的人, 看看你要去哪
    // (1) 访问的是无需授权的页面（白名单），也是放行
    //     就是判断，访问的地址，是否在白名单数组中存在 includes
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      next('/login')
    }
  }
})
Vue.component('ArticleItem', ArticleItem)
export default router
